# Configure the HuaweiCloud Provider
terraform {
  required_providers {
    huaweicloud = {
      source = "local-registry/huaweicloud/huaweicloud"
      version = "= 1.34.1"
    }
  }
}

provider "huaweicloud" {
  region     ="cn-north-4"
  access_key = ""
  secret_key = ""
}

#Create fgs agency
resource "huaweicloud_identity_agency" "agency" {
  name                   = "${var.template_name}_agency"
  delegated_service_name = "op_svc_cff"
  domain_roles           = ["OBS OperateAccess"]
  project_role {
     project             = "MOS"
     roles               =["OBS OperateAccess"]
 } 
}

#Create image bucket
resource "huaweicloud_obs_bucket" "ocr_app_image_bucket" {
  bucket = var.image_bucket_name
  acl    = "private"
  multi_az = true
}

#Create result bucket
resource "huaweicloud_obs_bucket" "ocr_app_result_bucket" {
  bucket = var.result_bucket_name
  acl    = "private"
  multi_az = true
}

#Create function
resource "huaweicloud_fgs_function" "ocr_app_fgs" {
  name        = "${var.template_name}-fgs"
  app         = "default"
  handler     = "ocr_app.handler"
  memory_size = 128
  timeout     = 120
  runtime     = "Python3.6"
  code_type   = "obs"
  agency      = huaweicloud_identity_agency.agency.name
  user_data = jsonencode({
    region = "cn-north-4"
    obs_server = "obs.cn-north-4.myhuaweicloud.com"
    result_bucket = var.result_bucket_name
  })
  depend_list = ["af0d3f19-af67-48f1-a0d7-c3918b2319f8","e9b20258-b719-4f4d-a19c-21740fcb45e7","3647fa03-ecdb-486c-a51e-b289e69b075c"]  
  code_url = "https://solution-as-code-publicbucket.obs.cn-north-4.myhuaweicloud.com/ocr-app/ocr_app.zip"
}

resource "huaweicloud_fgs_trigger" "fgs_trigger" {
  function_urn = huaweicloud_fgs_function.ocr_app_fgs.urn
  type         = "OBS"
  status       = "ACTIVE"
  obs { 
    bucket_name = var.image_bucket_name
    event_notification_name = "${var.template_name}_trigger"
    events = ["Post","Put"]
  }
}
